package com.baseframe.gateway.router;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class BaseRouterHandler implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher eventPublisher;
    private final RouteDefinitionWriter routeDefinitionWriter;





    @Override
    public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) {
        this.eventPublisher = applicationEventPublisher;
    }

    /**
     * 更新路由
     * @param routeDefinition 路由对象
     * @return 是否成功
     */
    @SuppressWarnings("Unused")
    public void update(RouteDefinition routeDefinition){

        try {
            this.routeDefinitionWriter.delete(Mono.just(routeDefinition.getId()));
            this.routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
            this.eventPublisher.publishEvent(new RefreshRoutesEvent(this));
            log.info("路由:{}更新成功~",routeDefinition.getId());
        }catch (Exception e){
            log.error("更新路由时发生了错误:{}",e.getMessage(),e);

        }
    }

    public void updateList(List<RouteDefinition> routeDefinitions) {
        routeDefinitions.forEach(this::update);
    }


}
